package cc.dullsky.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;

import net.iharder.Base64;

public class QRCodeUtil {
	private static final String FORMAT_PNG = "png";
	private static final String REGEX_URL = "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?";

	/**
	 * 生成用于前台显示的二维码base64编码
	 * 
	 * @param content
	 *            内容
	 * @param logoPath
	 *            logo路径,传入null则生成不带logo的二维码
	 * @param version
	 *            二维码版本，版本越大，二维码尺寸越大，尺寸=71 + 12 * version
	 * @return String 二维码base64编码，失败则返回"";
	 */
	public static String getQRCodeBase64(String content, String logoPath, int version) {
		BufferedImage image = getBufferedImage(content, logoPath, version);
		if (image == null) {
			return "";
		} else {
			return "data:image/png;base64," + Base64.encodeBytes(imageToBytes(image));
		}

	}

	/**
	 * 生成二维码并保存在本地
	 * 
	 * @param content
	 *            内容
	 * @param logoPath
	 *            logo路径,传入null则生成不带logo的二维码
	 * @param version
	 *            二维码版本，版本越大，二维码尺寸越大，尺寸=71 + 12 * version
	 * @param savePath
	 *            二维码保存路径
	 * @param fileName
	 *            二维码图片保存文件名
	 * @return boolean
	 */
	public static boolean saveQRCode(String content, String logoPath, int version, String savePath, String fileName) {
		BufferedImage image = getBufferedImage(content, logoPath, version);
		if (image == null) {
			return false;
		} else {
			mkdirs(savePath);
			// 生成二维码QRCode图片
			File imgFile = new File(savePath + File.separator + fileName);
			try {
				ImageIO.write(image, FORMAT_PNG, imgFile);
				return true;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
	}

	/**
	 * 获取BufferedImage对象
	 * 
	 * @param content
	 *            内容
	 * @param logoPath
	 *            logo路径
	 * @param version
	 *            二维码版本，版本越大，二维码尺寸越大，尺寸=51 + 12 * version + 2 * 10
	 * @return BufferedImage
	 */
	private static BufferedImage getBufferedImage(String content, String logoPath, int version) {
		try {
			Qrcode qrcodeHandler = new Qrcode();
			// 设置二维码排错率，可选L(7%)、M(15%)、Q(25%)、H(30%)，排错率越高可存储的信息越少，但对二维码清晰度的要求越小
			qrcodeHandler.setQrcodeErrorCorrect('H');
			// N代表数字,A代表字符a-Z,B代表其他字符
			qrcodeHandler.setQrcodeEncodeMode('B');
			// 设置设置二维码版本，取值范围1-40，值越大尺寸越大，可存储的信息越大
			qrcodeHandler.setQrcodeVersion(version);
			// 设置偏移量 不设置可能导致解析出错,可以理解为边框
			int pixoff = 10;
			// 图片尺寸
			int imgSize = 51 + 12 * version + 2 * pixoff;

			byte[] contentBytes = content.getBytes("utf-8");
			BufferedImage image = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);
			Graphics2D gs = image.createGraphics();

			gs.setBackground(Color.WHITE);
			gs.clearRect(0, 0, imgSize, imgSize);

			// 设定图像颜色 > BLACK
			gs.setColor(Color.BLACK);
			// 输出内容 > 二维码
			if (contentBytes.length > 0 && contentBytes.length < 130) {
				boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
				for (int i = 0; i < codeOut.length; i++) {
					for (int j = 0; j < codeOut.length; j++) {
						if (codeOut[j][i]) {
							gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
						}
					}
				}
			} else {
				System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,130]. ");
				return null;
			}
			if (logoPath != null) {
				Image logo = null;
				// 匹配网址logo
				if (logoPath.matches(REGEX_URL)) {
					String logoFileName = UUID.randomUUID().toString() + logoPath.substring(logoPath.lastIndexOf("."));
					String tempPath = new File("").getCanonicalPath();
					if (FileUtil.downLoadFromUrl(logoPath, logoFileName, tempPath)) {
						File loaclLogo = new File(tempPath + File.separator + logoFileName);
						logo = ImageIO.read(loaclLogo);// 实例化一个Image对象。
						loaclLogo.delete();
					} else {
						gs.dispose();
						image.flush();
						return image;
					}
				} else {
					logo = ImageIO.read(new File(logoPath));// 实例化一个Image对象。
				}
				/*
				 * int widthLogo = logo.getWidth(null) > image.getWidth() / 5 ?
				 * (image.getWidth() / 5) : logo.getWidth(null), heightLogo =
				 * logo.getHeight(null) > image.getHeight() / 5 ?
				 * (image.getHeight() / 5) : logo.getWidth(null);
				 */
				int widthLogo = image.getWidth() / 5, heightLogo = image.getHeight() / 5;
				/**
				 * logo放在中心
				 */
				int x = (image.getWidth() - widthLogo) / 2;
				int y = (image.getHeight() - heightLogo) / 2;
				gs.drawImage(logo, x, y, widthLogo, heightLogo, null);
			}
			gs.dispose();
			image.flush();
			return image;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 当文件夹不存在时,mkdirs会自动创建多层目录，区别于mkdir,(mkdir如果父目录不存在则会抛出异常)
	 * 
	 * @param destPath
	 *            存放目录
	 */
	private static void mkdirs(String destPath) {
		File file = new File(destPath);
		if (!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}
	}

	/**
	 * 转换Image数据为byte数组
	 * 
	 * @param image
	 *            Image对象
	 * @param format
	 *            image格式字符串.如"gif","png","jpg"
	 * @return byte数组
	 */
	private static byte[] imageToBytes(BufferedImage bufferedImage) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			ImageIO.write(bufferedImage, FORMAT_PNG, out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}

	public static void main(String[] args) {
		String savePath = "e:/";
		String fileName = "asd.png";
		String logoPath = "E:/1.jpg";
		String content = "http://note.dullsky.cc";
		/*
		 * String base64 = QRCodeUtil.getQRCodeBase64(content, null, 6);
		 * System.out.println(base64);
		 */
		QRCodeUtil.saveQRCode(content, null, 8, savePath, fileName);
	}
}
